package com.zisuyi.uilibrary.module.activty.welcome

import android.animation.ValueAnimator
import android.os.Bundle
import android.view.animation.AccelerateDecelerateInterpolator
import androidx.core.animation.doOnEnd
import com.weilele.mvvm.base.helper.*
import com.weilele.mvvm.base.helper.annotation.MvvmViewModel
import com.weilele.mvvm.utils.activity.onClick
import com.weilele.mvvm.utils.activity.textFrom
import com.weilele.mvvm.utils.activity.visible
import com.weilele.mvvm.utils.glide.setImageGlide
import com.zisuyi.game.sdk.game.GameReceiveMessage
import com.zisuyi.game.sdk.library.login.IGameLogin
import com.zisuyi.game.sdk.net.bean.UserInfoBean
import com.zisuyi.uilibrary.base.BaseUiGameActivity
import com.zisuyi.uilibrary.databinding.ActivityWelcomeBinding
import com.zisuyi.uilibrary.module.activty.login.LoginActivity
import com.zisuyi.uilibrary.module.activty.login.UserLoginViewModel
import com.zisuyi.uilibrary.module.dialog.SimpleTextDialog.Companion.simpleTextDialog
import com.zisuyi.uilibrary.module.dialog.rating.RatingDialog

class WelcomeActivity : BaseUiGameActivity<ActivityWelcomeBinding>() {
    @MvvmViewModel
    private lateinit var loginViewModel: UserLoginViewModel
    override fun initUi(savedInstanceState: Bundle?) {
        if (!checkApp()) {
            return
        }
        if (LoginActivity.isAutoGoogleLogin()) {
            LoginActivity.start(appCompatActivity)
            return
        }
        super.initUi(savedInstanceState)
        startLogin()
    }

    /**
     * 检测app是否被改过
     */
    private fun checkApp(): Boolean {
        val normal = "raL+GuWy4MiQXN15AQAKS+Ym6rk=" == GameReceiveMessage.hash
        if (!normal) {
            simpleTextDialog {
                isCancelable = false
                content = "Your application is abnormal,\nPlease download again in the app store"
                buttonText = "GO"
                buttonNext.onClick {
                    RatingDialog.goGooglePlay(this@WelcomeActivity)
                }
                setOnCLickCloseListener {
                    finish()
                }
            }
        }
        return normal
    }

    private fun startLogin() {
        mBinding.tvHint.textFrom("Check Account...")
        mBinding.pbWelcome.progress = 0
        initAnim()
    }

    /**
     * 登录出错自动重试，最多五次
     */
    private fun showError(message: String?) {
        showOtherView(message, retryText = "RETRY") {
            showContentView()
            startLogin()
        }
    }

    private var lastUser: IGameLogin.UserInfo? = null
//    by lazy {
//
//        /* ?: IGameLogin.UserInfo(
//                 "123456", "123456", IGameLogin.LOGIN_GOOGLE,
//                 "Test_123465", "")*/
//    }

    private fun initAnim() {
        isLoginRequestFinish = false
        isAnimFinish = false
        val user = IGameLogin.lastUserInfo()
        lastUser = user
        mBinding.pbWelcome.max = 100
        val max = if (user != null) {
            mBinding.ivUserHead.visible()
            mBinding.ivUserHead.setImageGlide(user.thumb)
            loginViewModel.userLogin(user)
            mBinding.pbWelcome.max - 48
        } else {
            isLoginRequestFinish = true
            loginViewModel.userInfoData.success(UserInfoBean())
            mBinding.pbWelcome.max
        }
        startAnim(max)
    }

    private fun startAnim(max: Int, isCheckUser: Boolean = true) {
        ValueAnimator.ofInt(mBinding.pbWelcome.progress, max).apply {
            addUpdateListener {
                mBinding.pbWelcome.progress = it.animatedValue as Int
                mBinding.tvProgress.textFrom("${mBinding.pbWelcome.progress * 100 / mBinding.pbWelcome.max}%")
            }
            doOnEnd {
                isAnimFinish = true
                if (isCheckUser) {
                    checkUser()
                }
            }
            interpolator = AccelerateDecelerateInterpolator()
            duration = 1600
        }.start()
    }

    private fun initHuaweiAnim() {
        isLoginRequestFinish = false
        isAnimFinish = false
        mBinding.pbWelcome.max = 100
        val max = mBinding.pbWelcome.max - 8
        startAnim(max)
    }


    override fun getObserverLiveData(): List<LiveDataWrap>? {
        return listOf(loginViewModel.userInfoData wrapObserver ::onUserLogin)
    }

    private var isAnimFinish = false
    private var isLoginRequestFinish = false
    private fun checkUser() {
        if (isAnimFinish && isLoginRequestFinish) {
            when (val value = loginViewModel.userInfoData.value) {
                is StatusValue.Success -> {
                    if (lastUser == null) {
                        mBinding.pbWelcome.progress = mBinding.pbWelcome.max
                        mBinding.tvProgress.textFrom("${mBinding.pbWelcome.progress * 100 / mBinding.pbWelcome.max}%")
                        toLoginPage()
                    } else {
                        toMainPage()
                    }
                }
                is StatusValue.Running -> {

                }
                is StatusValue.Error -> {
                    showError(value.nonNullMsg)
                }
            }
        }
    }

    private fun toMainPage() {
        mBinding.tvHint.textFrom("Loading Game...")
        loadGame()
        startAnim(mBinding.pbWelcome.max - 8, false)
    }

    private fun toLoginPage() {
        LoginActivity.start(appCompatActivity)
    }

    private fun onUserLogin(value: StatusValue<UserInfoBean>?) {
        when (value) {
            is StatusValue.Running -> {

            }
            is StatusValue.Error -> {
                isLoginRequestFinish = true
                checkUser()
            }
            is StatusValue.Success -> {
                isLoginRequestFinish = true
                checkUser()
            }
        }
    }

    override fun isNeedSwitchView(): Boolean {
        return true
    }
}